<?php

class sgeUser extends sfGuardSecurityUser
{

	public function signIn($user, $remember = false, $con = null)
	{
		$this->user = null;
		$this->clearCredentials();
		$this->addCredentials($user->getAllPermissionNames());

		$user->setLastLogin(date('Y-m-d H:i:s'));
		$user->save($con);

		$permissions = array_flip($this->credentials);
		$menu_schema = array();

		foreach (Constantes::$MENU_SCHEMA as $menu => $values)
		{
			foreach ($values as $item => $model)
			{
				if (isset($permissions[$item]))
				{
					if (!isset($menu_schema[$menu]))
						$menu_schema[$menu] = array();

					$menu_schema[$menu][$item] = $model;
				}
			}
		}

		$this->setAttribute('menu_schema', $menu_schema, 'sgeUser');

		$this->setAttribute('user_id', $user->id, 'sgeUser');
		$this->setAttribute('user_data', null, 'sgeUser');
		$this->setAuthenticated(true);
	}

	public function hasCredential($credential, $useAnd = true)
	{
		if (empty($credential))
		{
			return true;
		}

		if (!$this->getGuardUser())
		{
			return false;
		}

		return parent::hasCredential($credential, $useAnd);
	}

	public function getAllPermissionNames()
	{
		return $this->getGuardUser() ? $this->user->getAllPermissionNames() : array();
	}

	public function signOut()
	{
		$this->getAttributeHolder()->removeNamespace('sgeUser');
		$this->user = null;
		$this->clearCredentials();
		$this->setAuthenticated(false);
	}

	public function setReferer($referer)
	{
		if (!$this->hasAttribute('referer'))
		{
			$this->setAttribute('referer', $referer);
		}
	}

	public function getReferer($default)
	{
		$referer = $this->getAttribute('referer', $default);
		$this->getAttributeHolder()->remove('referer');

		return $referer;
	}

	public function getGuardUser()
	{
		if ($this->user == null && $id = $this->getAttribute('user_id', null, 'sgeUser'))
		{
			if ($this->hasAttribute('user_data', 'sgeUser'))
			{
				$this->user = $this->getAttribute('user_data', null, 'sgeUser');
			}
			else
			{
				//$this->user = sgeLdap::getInstance()->getUser($login);
				$this->user = Doctrine_Core::getTable('sfGuardUser')->find($id);

				if (!$this->user)
				{
					$this->signOut();
					throw new sfException('El usuario no existe.');
				}

				$this->setAttribute('user_data', $this->user, 'sgeUser');
			}
		}

		return $this->user;
	}

	public function getUserId()
	{
		return $this->getAttribute('user_id', -1, 'sgeUser');
	}

}

